<template>
  <div>
    <el-card class="box-card">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="操作描述">
          <el-input v-model="queryForm.operation" placeholder="请输入操作描述"></el-input>
        </el-form-item>
        <el-form-item label="模块">
          <el-select v-model="queryForm.module" placeholder="请选择模块" clearable class="select-input">
            <el-option label="角色模块" value="角色模块"></el-option>
            <el-option label="日志模块" value="日志模块"></el-option>
            <el-option label="用户模块" value="用户模块"></el-option>
            <el-option label="标签模块" value="标签模块"></el-option>
            <el-option label="项目模块" value="项目模块"></el-option>
            <el-option label="文章模块" value="文章模块"></el-option>
            <el-option label="系统日志模块" value="系统日志模块"></el-option>
            <el-option label="工具分类模块" value="工具分类模块"></el-option>
            <el-option label="项目分类模块" value="项目分类模块"></el-option>
            <el-option label="评论模块" value="评论模块"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请求方法">
          <el-select v-model="queryForm.method" placeholder="请选择请求方法" clearable class="select-input">
            <el-option label="GET" value="GET"></el-option>
            <el-option label="POST" value="POST"></el-option>
            <el-option label="PUT" value="PUT"></el-option>
            <el-option label="DELETE" value="DELETE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable class="select-input">
            <el-option label="成功" :value="1"></el-option>
            <el-option label="失败" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="logList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        highlight-current-row
        stripe
      >
        <el-table-column type="selection" ></el-table-column>
        <el-table-column prop="id" label="ID" ></el-table-column>
        <el-table-column prop="username" label="用户名" >
          <template #default="scope">
            <el-tag type="info" effect="plain">{{ scope.row.username }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="模块" >
          <template #default="scope">
            <el-tag type="success" effect="plain" size="small">{{ scope.row.module }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="url" label="URL地址"  show-overflow-tooltip></el-table-column>
        <el-table-column prop="method" label="请求方法" >
          <template #default="scope">
            <el-tag 
              :type="scope.row.method === 'GET' ? 'success' : scope.row.method === 'POST' ? 'warning' : scope.row.method === 'DELETE' ? 'danger' : 'info'"
              effect="plain"
              size="small"
            >{{ scope.row.method }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="dark">
              {{ scope.row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="操作时间" ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleView(scope.row)">
              <el-icon><View /></el-icon> 查看
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="操作日志详情" v-model="dialogVisible" width="65%" destroy-on-close>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">
          <el-tag type="info">{{ selectedLog.id }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          <el-tag type="info" effect="plain">{{ selectedLog.username }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="模块">
          <el-tag type="success" effect="plain">{{ selectedLog.module }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作描述">{{ selectedLog.operation }}</el-descriptions-item>
        <el-descriptions-item label="URL地址">
          <el-link type="primary" :underline="false">{{ selectedLog.url }}</el-link>
        </el-descriptions-item>
        <el-descriptions-item label="请求方法">
          <el-tag 
            :type="selectedLog.method === 'GET' ? 'success' : selectedLog.method === 'POST' ? 'warning' : selectedLog.method === 'DELETE' ? 'danger' : 'info'"
            effect="plain"
          >{{ selectedLog.method }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求参数">
          <el-card shadow="never" class="code-card">
            <pre class="code-block">{{ formatJson(selectedLog.requestParam) }}</pre>
          </el-card>
        </el-descriptions-item>
        <el-descriptions-item label="响应结果">
          <el-card shadow="never" class="code-card">
            <pre class="code-block">{{ formatJson(selectedLog.result) }}</pre>
          </el-card>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="selectedLog.status === 1 ? 'success' : 'danger'" effect="dark">
            {{ selectedLog.status === 1 ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="异常信息" v-if="selectedLog.status === 0">
          <el-alert
            type="error"
            :closable="false"
            show-icon
          >
            <pre class="error-message">{{ selectedLog.errorMsg }}</pre>
          </el-alert>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ selectedLog.createdTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getOpLogPageList, getOpLogById, deleteOpLogById, deleteOpLogBatch } from '@/api/opLog'
import { Search, Refresh, Delete, View } from '@element-plus/icons-vue'

// 查询表单
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  operation: '',
  module: '',
  method: '',
  status: '',
  startTime: '',
  endTime: ''
})

// 日期范围选择
const dateRange = ref([])
const handleDateChange = (val) => {
  if (val) {
    queryForm.startTime = val[0]
    queryForm.endTime = val[1]
  } else {
    queryForm.startTime = ''
    queryForm.endTime = ''
  }
}

// 状态数据
const loading = ref(false)
const logList = ref([])
const total = ref(0)
const selectedIds = ref([])
const dialogVisible = ref(false)
const selectedLog = ref({})

// 获取日志列表
const getList = async () => {
  loading.value = true
  try {
    // 创建一个新对象来保存要发送的参数
    const params = { ...queryForm }
    
    // 如果开始时间或结束时间为空，则从参数中删除
    if (!params.startTime) {
      delete params.startTime
    }
    if (!params.endTime) {
      delete params.endTime
    }
    
    const response = await getOpLogPageList(params)
    logList.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    console.error('获取操作日志列表失败', error)
    ElMessage.error('获取操作日志列表失败')
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryForm.pageNum = 1
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryForm.pageNum = 1
  queryForm.operation = ''
  queryForm.module = ''
  queryForm.method = ''
  queryForm.status = ''
  queryForm.startTime = ''
  queryForm.endTime = ''
  dateRange.value = []
  getList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页相关方法
const handleSizeChange = (size) => {
  queryForm.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  queryForm.pageNum = current
  getList()
}

// 查看详情
const handleView = async (row) => {
  try {
    const response = await getOpLogById(row.id)
    selectedLog.value = response.data
    dialogVisible.value = true
  } catch (error) {
    console.error('获取操作日志详情失败', error)
    ElMessage.error('获取操作日志详情失败')
  }
}

// 删除单条记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该操作日志记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteOpLogById(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条操作日志记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteOpLogBatch(selectedIds.value)
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
    }
  }).catch(() => {})
}

// JSON格式化显示
const formatJson = (jsonString) => {
  if (!jsonString) return '';
  try {
    // 尝试解析JSON字符串
    const jsonObj = typeof jsonString === 'string' ? JSON.parse(jsonString) : jsonString;
    // 格式化并加缩进
    return JSON.stringify(jsonObj, null, 2);
  } catch (e) {
    // 如果解析失败，直接返回原始字符串
    return jsonString;
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.code-block {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  margin: 0;
  color: #333;
  font-size: 14px;
  line-height: 1.5;
}

.error-message {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #fef0f0;
  padding: 10px;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  font-family: monospace;
  margin: 0;
}

.code-card {
  margin-bottom: 0;
  background-color: #f5f7fa;
}

.select-input {
  width: 220px;
}
</style> 